'use strict';
const Controller = require('egg').Controller;

class HomeController extends Controller {
  async login() {
    // 1. 解构
    const { ctx, app } = this;
    // 获取前端请求
    // 获取用户名
    const username = ctx.request.body.username;
    // 获取密码
    const password = ctx.request.body.password;

    // 测试获取结果的正确性
    console.log("用户名：" + username + "密码： " + password);
    const res = await app.mysql.get('test', { username: username });
    if(res){
        if (res.password == password) {
            console.log("登录成功：" + res.username);
            const res2 = await app.mysql.get('test', { username: username });
            ctx.body = {
                code: 200,
                message: '登录成功',
                data: res2.id  // (userid)
            }
        } else {
            console.log("用户名或密码错误");
            ctx.body = {
                code: 500,
                message: '用户名或密码错误',
                data: null
            }
        }
    }else {
        console.log("用户名或密码错误");
            ctx.body = {
                code: 500,
                message: '用户名或密码错误',
                data: null
            }
    }

        // 判断是否插入成功
        // if (res.affectedRows === 1) {
        //     console.log("插入成功");
        //     //
        // }
        // await ctx.render('user_input_page');

    }
    //   async user_page() {
    //     // 1. 解构
    //     const { ctx,service } = this;
    //     // 2. 渲染HTML
    //     await ctx.render('user_input_page');

    //   }
    //   async user_name() {
    //     // 1. 解构
    //     const { ctx,service } = this;
    //     // 2. 渲染HTML
    //     this.ctx.body = "你好";
    //     // return this.ctx.body;

    //   }
    async register() {
        // 1. 解构
        const { ctx, app } = this;
        // 2. 判断数据库中是否已有该用户名和密码
        const username = ctx.request.body.username;
        const password = ctx.request.body.password;
        // 用户注册的用户名必须为中文
        console.log("注册函数查询到的用户名和密码：" + username + password);
        // this.read(username,password);
        const res = await app.mysql.get('test', { username: username });
        // console.log("查询到的结果：" + res);
        // ctx.body = res;
        if (res == null) {
            console.log("正在注册......");
            // this.create(username, password);
            const res = await app.mysql.insert('test', { username: username, password: password });
            if (res.affectedRows === 1) {
                const res = await app.mysql.get('test', { username: username });
                console.log("注册成功");
                ctx.body = {
                    code: 200,
                    message: '注册成功',
                    data: res.id // (userid)
                };
            }
            console.log("注册成功：" + res.username);
        } else {
            console.log("用户名已存在");
            // this.ctx.body = "用户名已存在";
            ctx.body = {
                code: 500,
                message: '用户名已存在',
                data: null
            }
            // return "用户名已存在";
        }
    }

    // 随机查询一条贴士
    async tips() {
      // 1. 解构
      const { ctx, app } = this;
      const temp = await app.mysql.select('tip');
      console.log("查询到的条数：" + temp.length);
      let arr = [];
      for(let i = 0;i < temp.length; i++) {
          arr.push(i+1);
      }
      // console.log(arr);
      // const arr = [1, 2, 3, 4, 5, 6, 7];
      const res = await app.mysql.get('tip', { id: arr[Math.floor((Math.random() * arr.length))] });
      // const res = await app.mysql.get('tip', { id: 1});
      console.log("Tip的标题：" + res.title + "Tip的内容：" + res.content);
      if (res.title) {
          ctx.body = {
              code: 200,
              message: '查询成功',
              data: {
                  content: res.content
              }
          }
      } else {
          ctx.body = {
              code: 500,
              message: '查询失败',
              data: null
          }
      }
    }
    // 用户上传日记
    async diary() {
        // 1. 解构
        const { ctx, app } = this;
        // const res = await app.mysql.get('tip', { id: arr[Math.floor((Math.random()*arr.length))]});
        // 获取用户日记相关参数
        // 此处的用户id不可重复
        const userid = ctx.request.body.userid;
        const total_score = ctx.request.body.total_score;
        const each_score = ctx.request.body.each_score;
        const diary = ctx.request.body.diary;
        const res = await app.mysql.insert('daily', { userid: userid, total_score: total_score, each_score: each_score, diary: diary });
        if (res) {
            console.log("用户日记上传成功！");
            ctx.body = {
                code: 200,
                message: '上传成功',
                data: null
            }
        } else {
            ctx.body = {
                code: 500,
                message: '上传失败',
                data: null
            }
        }
    }

    // 查询日记函数
    async diary_Inquire() {
        // 1. 解构
        const { ctx, app } = this;
        // 获取请求参数
        const userid = ctx.queries.userId;
        const date = ctx.queries.date;
        console.log("用户的请求参数：" + userid + date);
        // 此时的temp是一个数组
        const temp = await app.mysql.select('daily', { where: { userid: userid } });
        var flag = 0;
        // 遍历这个temp数组
        for (let x in temp) {
            console.log("x是：" + temp[x].create_time);
            console.log(JSON.stringify(temp[x].create_time));
            const temp_time = JSON.stringify(temp[x].create_time);
            if ((temp_time.indexOf(date) != -1) & (temp[x].userid == userid)) {
                flag = 1;
                ctx.body = {
                    code: 200,
                    message: '查询成功',
                    data: {
                        diaryId: temp[x].userid,
                        eachScore: temp[x].each_score, //json格式的字符串
                        diary: temp[x].diary,
                        totalScore: temp[x].total_score,
                        createTime: temp[x].create_time
                    }
                }
            }
        }
        if(flag !== 1) {
            ctx.body = {
                code: 500,
                message: '查询失败',
                data: null
            }
        }
    }

    // 意见反馈
    async feedback() {
      const { ctx, app } = this;
      const phone = ctx.request.body.phone;
      const content = ctx.request.body.content;
      const userid = ctx.request.body.userid;
      console.log("用户反馈的意见："+ phone + content + userid);
      const res = await app.mysql.insert('feedback', { userid: userid, phone: phone,content: content });
      if(res) {
          ctx.body = {
              code: 200,
              message: '提交成功',
              data: null
          }
      }else {
          ctx.body = {
              code: 500,
              message: '提交失败',
              data: null
          }
      }
  }





    // 更新数据库的内容
    async update() {
        const { ctx, app } = this;
        // 在更新的时候 id作为主键是查询的关键
        const row = {
            id: 4,
            username: 'zhangsan',
            password: 123456789,
            // modifiedAt: app.mysql.literals.now,
        };
        const result = await app.mysql.update('test', row);
    }
    // 删除用户的数据
    async delete() {
        const { ctx, app } = this;

        const result = await app.mysql.delete('test', {
            username: 'zhangsanf20',
        });
    }

}

module.exports = HomeController;